import random
from multiprocessing.pool import ThreadPool, AsyncResult
import time
from typing import List
from common.utility import Utility

# 主函数
def main(thread_count: int = 5, sync: bool = True):
    Utility.print_info('entered.')
    with ThreadPool(initializer=threadpool_init) as pool:
        sleep_time_list: List[tuple[int, int]] = []
        for i in range(thread_count):
            sleep_time_list.append((i, random.randint(1,10)))
        if sync:
             Utility.print_info(f'线程池返回值：{pool.starmap(task, sleep_time_list)}')
        else:
            results: AsyncResult = pool.starmap_async(task, sleep_time_list, callback=callback, error_callback=error_callback)
            Utility.print_info(f'线程池返回值：{results.get()}')
    Utility.print_info('exited.')

# 线程池初始化
def threadpool_init() -> None:
    Utility.print_info('线程池初始化。')

# 线程池回调函数
def callback(_) -> None:
    Utility.print_info(f'线程池回调函数。{_}')

# 线程池错误回调函数
def error_callback(ex: BaseException) -> None:
    Utility.print_info(f'线程池错误回调函数：{ex}')

# 任务
def task(idx: int, sleep_time: int) -> tuple[int, str, int]:
    Utility.print_info(f'entered. It will sleep {sleep_time} seconds.')
    time.sleep(sleep_time)
    Utility.print_info('exited.')
    return idx, f'task {idx}', sleep_time

main(2, sync=True)
